﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace _List转Model
{
    class Program
    {
        static void Main(string[] args)
        {
            //一行list转model
            List<Person> persons = new List<Person>() {
                  new Person() { Id=1, Name="张三", Birthday=DateTime.Now.AddYears(-23), Sex="男", InputTime=DateTime.Now }
            };

            Person per = GetModels2<Person>(persons);

        }


        public static T GetModels2<T>(List<Person> model) where T : new()
        {
            T t = new T();
            System.Reflection.PropertyInfo[] Info = t.GetType().GetProperties();
            System.Reflection.PropertyInfo[] InfoModel = model[0].GetType().GetProperties();

            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            foreach (PropertyInfo p2 in InfoModel)
            {
                Dictionary<string, object> row = new Dictionary<string, object>();
                row.Add(p2.Name, p2.GetValue(model[0], null));
                rows.Add(row);
            }

            foreach (PropertyInfo p in Info)
            {
                foreach (PropertyInfo p2 in InfoModel)
                {
                    //////报错报错好烦
                    //p.SetValue(t, p2.GetValue(model[0],null));
                    if (p.Name == p2.Name)
                    {
                        p.SetValue(t, p2.GetValue(model[0], null));
                    }
                }
            }
            return t;
        }


        public static Person GetModels(List<Person> model)
        {
            Person per = new Person();
            per.Name = model[0].Name;
            per.Sex = model[0].Sex;
            per.Id = model[0].Id;
            per.Birthday = model[0].Birthday;
            per.InputTime = model[0].InputTime;

            return per;
        }
    }
}
